<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="蜂农姓名" prop="farmerName">
        <el-input v-model="queryParams.farmerName" placeholder="请输入蜂农姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="蜂农联系电话" prop="farmerPhone" label-width="100px">
        <el-input v-model="queryParams.farmerPhone" placeholder="请输入蜂农联系电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="蜂农身份证号" prop="farmerIdCard" label-width="100px">
        <el-input v-model="queryParams.farmerIdCard" placeholder="请输入蜂农身份证号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in farmer_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['farmer:farmer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['farmer:farmer:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['farmer:farmer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['farmer:farmer:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="loadTableData"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="farmerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80px" />
      <el-table-column label="蜂农姓名" align="center" prop="farmerName" />
      <el-table-column label="蜂农联系电话" align="center" prop="farmerPhone" />
      <el-table-column label="蜂农身份证号" align="center" prop="farmerIdCard" />
      <el-table-column label="蜂农住址" align="center" prop="farmerAddress" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="farmer_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)"
                     v-hasPermi="['farmer:farmer:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
                     v-hasPermi="['farmer:farmer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改蜂农信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="farmerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="蜂农姓名" prop="farmerName">
          <el-input v-model="form.farmerName" placeholder="请输入蜂农姓名" />
        </el-form-item>
        <el-form-item label="蜂农住址" prop="farmerAddress">
          <el-input v-model="form.farmerAddress" placeholder="请输入蜂农住址" />
        </el-form-item>
        <el-form-item label="蜂农状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in farmer_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="蜂农联系电话" prop="farmerPhone" label-width="110px">
          <el-input v-model="form.farmerPhone" placeholder="请输入蜂农联系电话" />
        </el-form-item>
        <el-form-item label="蜂农身份证号" prop="farmerIdCard" label-width="110px">
          <el-input v-model="form.farmerIdCard" placeholder="请输入蜂农身份证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Farmer">
import { listFarmer, getFarmer, delFarmer, addFarmer, updateFarmer } from "@/api/farmer/farmer"
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'; // 确保导入必要的API
import axios from 'axios'; // 导入axios

const { proxy } = getCurrentInstance()
const { farmer_status } = proxy.useDict('farmer_status')

const farmerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 存储表格数据的响应式变量（与现有farmerList可共用或单独使用）
const tableData = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    farmerName: null,
    farmerPhone: null,
    farmerIdCard: null,
    farmerAddress: null,
    status: null,
  },
  rules: {
    farmerName: [
      { required: true, message: "蜂农姓名不能为空", trigger: "blur" }
    ],
    farmerPhone: [
      { required: true, message: "蜂农联系电话不能为空", trigger: "blur" }
    ],
    farmerIdCard: [
      { required: true, message: "蜂农身份证号不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 新增：加载表格数据的函数（带时间戳防缓存） */
function loadTableData() {
  // 发送 GET 请求到后端接口，添加时间戳参数 t
  axios.get('/api/farmer/list', {
    params: {
      t: new Date().getTime(), // 时间戳，每次请求都不同，避免缓存
      ...queryParams.value // 携带现有查询参数（如分页、搜索条件）
    }
  }).then(res => {
    // 请求成功后，将响应数据赋值给表格（可选择更新farmerList或tableData）
    farmerList.value = res.data.rows; // 适配现有表格数据结构
    total.value = res.data.total;
    loading.value = false;
  }).catch(error => {
    // 处理请求失败的情况
    console.error('请求数据失败：', error);
    proxy.$modal.msgError('数据加载失败，请重试');
    loading.value = false;
  });
}

/** 查询蜂农信息列表（现有逻辑） */
function getList() {
  loading.value = true
  listFarmer(queryParams.value).then(response => {
    farmerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 可在需要时替换现有数据加载逻辑，例如在页面挂载时使用新函数
onMounted(() => {
  // 注释原有getList()，改用loadTableData()
  // getList();
  loadTableData();
});

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    farmerName: null,
    farmerPhone: null,
    farmerIdCard: null,
    farmerAddress: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("farmerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  // 可替换为loadTableData()
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加蜂农信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFarmer(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改蜂农信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["farmerRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFarmer(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFarmer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除蜂农信息编号为"' + _ids + '"的数据项？').then(function () {
    return delFarmer(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('farmer/farmer/export', {
    ...queryParams.value
  }, `farmer_${new Date().getTime()}.xlsx`)
}

// 初始加载（已通过onMounted控制）
</script>
